import copy
from io import BufferedReader
import requests
import json
from src.config import config
from src.exts import checkResponseJson,myredis

class MxtfApi():
    
    def __init__(self):
        self.url = config.MXTF_API
        self.results = ''
        self.cache = myredis
        self.cacheKey = 'dataimport:token'
        self.login()
        
        self.api_dict = {# key = (scenario, action)
            ("calculation_results","callback"):{
                "method":"get",
                "path":"/stock_loss_caculation/caculate_callback",
                "desc":"回写损失计算结果",
                "submit":{
                    "caculateId":871575821960089600,
                    "ammount":100000.15,
                    "measureType":"纪律处分",
                    "measureSubtype":"公开谴责",
                    "beginDate":19700416,
                    "endDate":19840219
                    },
                "return":[{
                    "date": "2024-01-01 00:00:00",
                    "stockId": "000001",
                    "open": 1.1,
                    "close": 1.2,
                    "high": 1.3,
                    "low": 0.9,
                    "quantity": 1000,
                    "amount": 10000,
                    "amplitude": 0.3,
                    "changePct": 0.09,
                    "changeAmmount": 0.08,
                    "turnover": 0.00012
                    },{
                    "date": "2024-01-02 00:00:00",
                    "stockId": "000001",
                    "open": 1.1,
                    "close": 1.2,
                    "high": 1.3,
                    "low": 0.9,
                    "quantity": 1000,
                    "amount": 10000,
                    "amplitude": 0.3,
                    "changePct": 0.09,
                    "changeAmmount": 0.08,
                    "turnover": 0.00012
                    }]
                },
                       
            ("stock_hist","select"):{
                "method":"get",
                "path":"/stocks_custom_history/get",
                "desc":"查询个股历史行情",
                "submit":{
                    "stock_id":"测试数据",
                    "start_date":"2024-01-01 00:00:00",
                    "end_date":"2024-12-31 23:59:59"
                    },
                "return":[{
                    "date": "2024-01-01 00:00:00",
                    "stockId": "000001",
                    "open": 1.1,
                    "close": 1.2,
                    "high": 1.3,
                    "low": 0.9,
                    "quantity": 1000,
                    "amount": 10000,
                    "amplitude": 0.3,
                    "changePct": 0.09,
                    "changeAmmount": 0.08,
                    "turnover": 0.00012
                    },{
                    "date": "2024-01-02 00:00:00",
                    "stockId": "000001",
                    "open": 1.1,
                    "close": 1.2,
                    "high": 1.3,
                    "low": 0.9,
                    "quantity": 1000,
                    "amount": 10000,
                    "amplitude": 0.3,
                    "changePct": 0.09,
                    "changeAmmount": 0.08,
                    "turnover": 0.00012
                    }]
                },
                        
            ("stock_hist","insert"):{
                "method":"post",
                "path":"/stocks_custom_history/batch_add",
                "desc":"批量添加个股历史行情",
                "submit":[{
                    "date": 1704038400,
                    "stockId": "000001",
                    "open": 1.1,
                    "close": 1.2,
                    "high": 1.3,
                    "low": 0.9,
                    "quantity": 1000,
                    "amount": 10000,
                    "amplitude": 0.3,
                    "changePct": 0.09,
                    "changeAmmount": 0.08,
                    "turnover": 0.00012
                    },{
                    "date": 1704124800,
                    "stockId": "000001",
                    "open": 1.1,
                    "close": 1.2,
                    "high": 1.3,
                    "low": 0.9,
                    "quantity": 1000,
                    "amount": 10000,
                    "amplitude": 0.3,
                    "changePct": 0.09,
                    "changeAmmount": 0.08,
                    "turnover": 0.00012
                    }],
                "return":""
                },
                        
            ("mkt_index_hist","select"):{
                "method":"get",
                "path":"/overall_market_trend/get",
                "desc":"查询大盘指数历史行情",
                "submit":{
                    "symbol":"测试数据2024-11-22 11:43:49",
                    "start_date":"1970-01-01 00:00:00",
                    "end_date":"2024-01-31 23:59:59"
                    },
                "return":[{
                    "date": "2024-01-01 00:00:00",
                    "open": 1.1,
                    "close": 1.1,
                    "high": 1.1,
                    "low": 1.1,
                    "volume": 100,
                    "amount": 1000,
                    "symbol": "sh000001"
                    },{
                    "date": "2024-01-01 00:00:00",
                    "open": 1.1,
                    "close": 1.1,
                    "high": 1.1,
                    "low": 1.1,
                    "volume": 100,
                    "amount": 1000,
                    "symbol": "sh000001"
                    }]
                },
            
            ("mkt_index_hist","insert"):{
                "method":"post",
                "path":"/overall_market_trend/batch_add",
                "desc":"批量添加大盘指数历史行情",
                "submit":[{
                    "date": "2024-01-01 00:00:00",
                    "open": 1.1,
                    "close": 1.1,
                    "high": 1.1,
                    "low": 1.1,
                    "volume": 100,
                    "amount": 1000,
                    "symbol": "sh000001"
                    },{
                    "date": "2024-01-01 00:00:00",
                    "open": 1.1,
                    "close": 1.1,
                    "high": 1.1,
                    "low": 1.1,
                    "volume": 100,
                    "amount": 1000,
                    "symbol": "sh000001"
                    }],
                "return":""
                },    
            
            ("sw_ind_index_hist","select"):{
                "method":"get",
                "path":"/shenwan_index_history/get",
                "desc":"查询申万行业指数历史行情",
                "submit":{
                    "swIndIndexId":"测试数据2024-11-27 14:11:41",
                    "start_date":"1970-01-01 00:00:00",
                    "end_date":"2024-01-31 23:59:59"
                    },
                "return":[{
                    "swIndIndexId": "801010",
                    "date": "2024-01-01 00:00:00",
                    "open": 1.1,
                    "close": 1.1,
                    "high": 1.1,
                    "low": 1.1,
                    "volume": 100,
                    "amount": 1000
                    },{
                    "swIndIndexId": "801010",
                    "date": "2024-01-02 00:00:00",
                    "open": 1.1,
                    "close": 1.1,
                    "high": 1.1,
                    "low": 1.1,
                    "volume": 100,
                    "amount": 1000
                    }]
                },
            
            ("sw_ind_index_hist","insert"):{
                "method":"post",
                "path":"/shenwan_index_history/batch_add",
                "desc":"批量添加申万行业指数历史行情",
                "submit":[{
                    "swIndIndexId": "801010",
                    "date": "2024-01-01 00:00:00",
                    "open": 1.1,
                    "close": 1.1,
                    "high": 1.1,
                    "low": 1.1,
                    "volume": 100,
                    "amount": 1000
                    },{
                    "swIndIndexId": "801010",
                    "date": "2024-01-02 00:00:00",
                    "open": 1.1,
                    "close": 1.1,
                    "high": 1.1,
                    "low": 1.1,
                    "volume": 100,
                    "amount": 1000
                    }],
                "return":""
                },
            
            ("sw_ind_comp_change_hist","select"):{
                "method":"get",
                "path":"/shenwan_history/get",
                "desc":"查询申万行业成本股变动历史",
                "submit":"",
                "return":[{
                    "symbol": "测试数据2024-11-27 14:11:36",
                    "startDate": "2001-01-01 00:00:00",
                    "industryCode": "440101",
                    "updateTime": "2001-01-01 00:00:00"
                    },{
                    "symbol": "000001",
                    "startDate": "2001-01-01 00:00:00",
                    "industryCode": "440101",
                    "updateTime": "2001-01-01 00:00:00"
                    }]
                },
            
            ("sw_ind_comp_change_hist","insert"):{
                "method":"post",
                "path":"/shenwan_history/batch_add",
                "desc":"批量添加申万行业成本股变动历史",
                "submit":[{
                    "symbol": "000001",
                    "startDate": "2001-01-01 00:00:00",
                    "industryCode": "440101",
                    "updateTime": "2001-01-01 00:00:00"
                    },{
                    "symbol": "000001",
                    "startDate": "2001-01-01 00:00:00",
                    "industryCode": "440101",
                    "updateTime": "2001-01-01 00:00:00"
                    }],
                "return":""
                },
            
            ("sw_ind_comp","select"):{
                "method":"get",
                "path":"/shenwan_industry/get",
                "desc":"查询申万行业成分股",
                "submit":"",
                "return":[{
                    "industryCode": "801010.SI",
                    "industryName": "农林牧渔",
                    "compCount": 101,
                    "staticPeRatio": 10.23,
                    "ttmPeRatio": 21.11,
                    "pbRatio": 2.12,
                    "staticDividendYield": 1.14,
                    "industryLayer": "l1"
                    },{
                    "industryCode": "801030.SI",
                    "industryName": "基础化工",
                    "compCount": 101,
                    "staticPeRatio": 10.23,
                    "ttmPeRatio": 21.11,
                    "pbRatio": 2.12,
                    "staticDividendYield": 1.14,
                    "industryLayer": "l1"
                    }]
                },
            
            ("sw_ind_comp","insert"):{
                "method":"post",
                "path":"/shenwan_industry/batch_add",
                "desc":"批量添加申万行业成分股",
                "submit":[{
                    "industryCode": "801010.SI",
                    "industryName": "农林牧渔",
                    "compCount": 101,
                    "staticPeRatio": 10.23,
                    "ttmPeRatio": 21.11,
                    "pbRatio": 2.12,
                    "staticDividendYield": 1.14,
                    "industryLayer": "l1"
                    },{
                    "industryCode": "801030.SI",
                    "industryName": "基础化工",
                    "compCount": 101,
                    "staticPeRatio": 10.23,
                    "ttmPeRatio": 21.11,
                    "pbRatio": 2.12,
                    "staticDividendYield": 1.14,
                    "industryLayer": "l1"
                    }],
                "return":""
                },
            
            ("sw_ind_index_dict","select"):{
                "method":"get",
                "path":"/shenwan_industry_index_map/get",
                "desc":"查询申万行业代码和行业指数代码对应关系",
                "submit":"",
                "return":[{
                    "industry_id":"220313",
                    "first_industry":"基础化工",
                    "second_industry":"化学制品",
                    "third_industry":"聚氨酯",
                    "industry_index_id":"850372",
                    "industry_index_type":"三级行业",
                    "posted":"1",
                    "change_reason":"2021保留",
                    "comp_count":"8"
                    },{
                    "industry_id":"220314",
                    "first_industry":"基础化",
                    "second_industry":"化制品",
                    "third_industry":"聚氨酯",
                    "industry_index_id":"850372",
                    "industry_index_type":"三级行业",
                    "posted":"1",
                    "change_reason":"2021保留",
                    "comp_count":"8"
                    }]
                },
            
            ("sw_ind_index_dict","insert"):{ # 暂不需要，需求待定
                "method":"post",
                "path":"/shenwan_industry_index_map/batch_add",
                "desc":"批量添加申万行业代码和行业指数代码对应关系",
                "submit":[{
                    "industry_id":"220313",
                    "first_industry":"基础化工",
                    "second_industry":"化学制品",
                    "third_industry":"聚氨酯",
                    "industry_index_id":"850372",
                    "industry_index_type":"三级行业",
                    "posted":"1",
                    "change_reason":"2021保留",
                    "comp_count":"8"
                    },{
                    "industry_id":"220314",
                    "first_industry":"基础化",
                    "second_industry":"化制品",
                    "third_industry":"聚氨酯",
                    "industry_index_id":"850372",
                    "industry_index_type":"三级行业",
                    "posted":"1",
                    "change_reason":"2021保留",
                    "comp_count":"8"
                    }],
                "return":""
                },
            
            ("exchange_file_index","select"):{
                "method":"get",
                "path":"",
                "desc":"查询监管措施文件索引",
                "submit":{
                    "stock_code":"600624",
                    "start_date":"2024-11-01 00:00:00",
                    "end_date":"2024-12-31 00:00:00"
                    },
                "return":[{
                    "stock_code":"600624",
                    "corp_name":"复旦复华",
                    "measure_subtype":"监管警示",
                    "measure_title":"关于对上海复旦复华科技股份有限公司及有关责任人予以监管警示的决定",
                    "measure_target":"上市公司,董秘",
                    "measure_date":"2024-11-21 00:00:00",
                    "measure_file_url":"http://www.sse.com.cn/disclosure/credibility/supervision/measures/focus/c/10764742/files/0e208c64631f4712ac83cf677d4b87d6.pdf",
                    "measure_file_name":"0e208c64631f4712ac83cf677d4b87d6.pdf",
                    "measure_entity":"sh",
                    "measure_type":"jgcs",
                    "measure_file_local_name":"0e208c64631f4712ac83cf677d4b87d6__20241125215612243073.pdf"
                    },{
                    "stock_code":"600624",
                    "corp_name":"复旦复华",
                    "measure_subtype":"监管警示",
                    "measure_title":"关于对上海复旦复华科技股份有限公司及有关责任人予以监管警示的决定",
                    "measure_target":"上市公司,董秘",
                    "measure_date":"2024-12-21 00:00:00",
                    "measure_file_url":"http://www.sse.com.cn/disclosure/credibility/supervision/measures/focus/c/10764742/files/0e208c64631f4712ac83cf677d4b87d6.pdf",
                    "measure_file_name":"0e208c64631f4712ac83cf677d4b87d6.pdf",
                    "measure_entity":"sh",
                    "measure_type":"jgcs",
                    "measure_file_local_name":"0e208c64631f4712ac83cf677d4b87d6__20241125215612243073.pdf"
                    }]
                },
            
            ("exchange_file_index","insert"):{
                "method":"post",
                "path":"",
                "desc":"批量添加监管措施文件索引",
                "submit":[{
                    "stock_code":"600624",
                    "corp_name":"复旦复华",
                    "measure_subtype":"监管警示",
                    "measure_title":"关于对上海复旦复华科技股份有限公司及有关责任人予以监管警示的决定",
                    "measure_target":"上市公司,董秘",
                    "measure_date":"2024-11-21 00:00:00",
                    "measure_file_url":"http://www.sse.com.cn/disclosure/credibility/supervision/measures/focus/c/10764742/files/0e208c64631f4712ac83cf677d4b87d6.pdf",
                    "measure_file_name":"0e208c64631f4712ac83cf677d4b87d6.pdf",
                    "measure_entity":"sh",
                    "measure_type":"jgcs",
                    "measure_file_local_name":"0e208c64631f4712ac83cf677d4b87d6__20241125215612243073.pdf"
                    },{
                    "stock_code":"600624",
                    "corp_name":"复旦复华",
                    "measure_subtype":"监管警示",
                    "measure_title":"关于对上海复旦复华科技股份有限公司及有关责任人予以监管警示的决定",
                    "measure_target":"上市公司,董秘",
                    "measure_date":"2024-12-21 00:00:00",
                    "measure_file_url":"http://www.sse.com.cn/disclosure/credibility/supervision/measures/focus/c/10764742/files/0e208c64631f4712ac83cf677d4b87d6.pdf",
                    "measure_file_name":"0e208c64631f4712ac83cf677d4b87d6.pdf",
                    "measure_entity":"sh",
                    "measure_type":"jgcs",
                    "measure_file_local_name":"0e208c64631f4712ac83cf677d4b87d6__20241125215612243073.pdf"
                    }],
                "return":""
                },
            
            ("exchange_measure_hist","select"):{ 
                "method":"get",
                "path":"/measure_history/get",
                "desc":"查询监管措施数据",
                "submit":{
                    "stock_code":"600543",
                    "start_date":"2024-08-01 00:00:00",
                    "end_date":"2024-08-31 00:00:00"
                    },
                "return":[{
                    "measure_entity":"上交所",
                    "measure_date":"2024-08-07 00:00:00",
                    "stock_code":"600543",
                    "corp_name":"莫高股份",
                    "measure_subtype":"监管警示",
                    "measure_file_name":"53517edd9e31486d8296e291b4e21e3e.pdf",
                    "measure_file_local_name":"53517edd9e31486d8296e291b4e21e3e__2012341233412.pdf",
                    "descp_ai":"否。理由是：根据所给信息，该函件主要关注的是短线交易行为及其违规性质。",
                    "judge_result_ai":"否",
                    "xujiachenshu_date_ai":"2024-03-15 00:00:00",
                    "gengzheng_date_ai":"2024-04-15 00:00:00",
                    "judge_result":"否",
                    "judge_result":"2024-03-15 00:00:00",
                    "xujiachenshu_date":"2024-04-15 00:00:00"
                    },{
                    "measure_entity":"上交所",
                    "measure_date":"2024-08-08 00:00:00",
                    "stock_code":"600543",
                    "corp_name":"莫高股份",
                    "measure_type":"监管警示",
                    "measure_subtype":"监管警示",
                    "measure_file_name":"53517edd9e31486d8296e291b4e21e3e.pdf",
                    "measure_file_local_name":"53517edd9e31486d8296e291b4e21e3e__2012341233412.pdf",
                    "descp_ai":"否。理由是：根据所给信息，该函件主要关注的是短线交易行为及其违规性质。",
                    "judge_result_ai":"否",
                    "xujiachenshu_date_ai":"2024-03-15 00:00:00",
                    "gengzheng_date_ai":"2024-04-15 00:00:00",
                    "judge_result":"否",
                    "judge_result":"2024-03-15 00:00:00",
                    "xujiachenshu_date":"2024-04-15 00:00:00"
                    }]
                },
            
            ("exchange_measure_hist","insert"):{ # 暂不需要，需求待定
                "method":"post",
                "path":"/measure_history/batch_add",
                "desc":"批量添加监管措施数据",
                "submit":[{
                    "measure_entity":"上交所",
                    "measure_date":"2024-08-07 00:00:00",
                    "stock_code":"600543",
                    "corp_name":"莫高股份",
                    "measure_type":"监管警示",
                    "measure_subtype":"监管警示",
                    "measure_file_name":"53517edd9e31486d8296e291b4e21e3e.pdf",
                    "measure_file_local_name":"53517edd9e31486d8296e291b4e21e3e__2012341233412.pdf",
                    "descp_ai":"否。理由是：根据所给信息，该函件主要关注的是短线交易行为及其违规性质。",
                    "judge_result_ai":"否",
                    "xujiachenshu_date_ai":"2024-03-15 00:00:00",
                    "gengzheng_date_ai":"2024-04-15 00:00:00",
                    "judge_result":"否",
                    "judge_result":"2024-03-15 00:00:00",
                    "xujiachenshu_date":"2024-04-15 00:00:00"
                    },{
                    "measure_entity":"上交所",
                    "measure_date":"2024-08-08 00:00:00",
                    "stock_code":"600543",
                    "corp_name":"莫高股份",
                    "measure_subtype":"监管警示",
                    "measure_file_name":"53517edd9e31486d8296e291b4e21e3e.pdf",
                    "measure_file_local_name":"53517edd9e31486d8296e291b4e21e3e__2012341233412.pdf",
                    "descp_ai":"否。理由是：根据所给信息，该函件主要关注的是短线交易行为及其违规性质。",
                    "judge_result_ai":"否",
                    "xujiachenshu_date_ai":"2024-03-15 00:00:00",
                    "gengzheng_date_ai":"2024-04-15 00:00:00",
                    "judge_result":"否",
                    "judge_result":"2024-03-15 00:00:00",
                    "xujiachenshu_date":"2024-04-15 00:00:00"
                    }],
                "return":""
                },

            ("stock_price_adj_factor","select"):{ 
                "method":"get",
                "path":"/stocks_custom_history_factor/get-by-date",
                "desc":"查询股价复权因子",
                "submit":{
                    "stock_code":"sh600543",
                    "start_date":"2024-08-01 00:00:00",
                    "end_date":"2024-08-31 00:00:00",
                    "factor_type":"qfq"
                    },
                "return":[]
                },

            ("xujiachenshu_action","select"):{ 
                "method":"get",
                "path":"/measure_action_real/get",
                "desc":"查询虚假陈述行为",
                "submit":{
                    "stock_code":"600543",
                    "start_date":"2024-08-01 00:00:00",
                    "end_date":"2024-08-31 00:00:00"
                    },
                "return":[]
                }
            
            }
    def useConfigToken(self):
        print('use config token')
        # self.token = config.Token
        token = self.cache.get(self.cacheKey)
        if not token:
            self.reLogin()
        else:
            self.token = token.decode('utf-8')
            self.headers = {
                'token': f'{self.token}',
                'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
                'Content-Type': 'application/json',
                'Authorization': f'Bearer {self.token}'
                }
    def login(self):
        self.useConfigToken()
    def reLogin(self):
        print('token expire relogin mxtf')
        url = f"{config.MXTF_API}/auth/login"
        payload = json.dumps({
            "username": config.UserName,
            "password": config.UserPwd,
            "rememberMe": True,
            "captcha": "aB7x9mQ2pL",
            "captchaId": "24"
            })
        headers = {
            'token': 'eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI2NDU0NzA5MDU2MTAyNzY4NjQiLCJzdWIiOiJhZG1pbiIsImlhdCI6MTczMjY4MzQyOCwicm9sZU5hbWUiOiJTdXBlciBBZG1pbiIsImF1dGhvcml0aWVzIjpbeyJhdXRob3JpdHkiOiJkYXNoYm9hcmQ6aG9tZSJ9LHsiYXV0aG9yaXR5IjoidmVyc2lvbjpidG46YWRkIn0seyJhdXRob3JpdHkiOiJtZXNzYWdlOmJ0bjphZGQifSx7ImF1dGhvcml0eSI6ImJhbm5lcjpidG46YWRkIn0seyJhdXRob3JpdHkiOiJhcnRpY2xlOmJ0bjphZGQifSx7ImF1dGhvcml0eSI6InNldHRpbmc6YnRuOmJhc2ljIn0seyJhdXRob3JpdHkiOiJiYW5uZXItcG9zaXRpb246YnRuOmFkZCJ9LHsiYXV0aG9yaXR5IjoiYmFubmVyLXBvc2l0aW9uOmxpc3QifSx7ImF1dGhvcml0eSI6InVzZXI6YnRuOmFkZCJ9LHsiYXV0aG9yaXR5IjoiYXJ0aWNsZS1jYXRlZ29yeTpsaXN0In0seyJhdXRob3JpdHkiOiJhcnRpY2xlLWNhdGVnb3J5OmJ0bjphZGQifSx7ImF1dGhvcml0eSI6InZlcnNpb246YnRuOmVkaXQifSx7ImF1dGhvcml0eSI6ImFydGljbGU6YnRuOmVkaXQifSx7ImF1dGhvcml0eSI6ImxvZzpidG46ZGVsZXRlIn0seyJhdXRob3JpdHkiOiJhcnRpY2xlOmxpc3QifSx7ImF1dGhvcml0eSI6ImJhbm5lcjpsaXN0In0seyJhdXRob3JpdHkiOiJwcm90ZWN0aW9uOmxpc3QifSx7ImF1dGhvcml0eSI6ImFjY291bnQ6c2V0dGluZyJ9LHsiYXV0aG9yaXR5IjoiYmFubmVyLXBvc2l0aW9uOmJ0bjplZGl0In0seyJhdXRob3JpdHkiOiJmZWVkYmFjazpidG46ZWRpdCJ9LHsiYXV0aG9yaXR5Ijoic3lzdGVtOmFkbWluIn0seyJhdXRob3JpdHkiOiJ1c2VyOmxpc3QifSx7ImF1dGhvcml0eSI6InVzZXI6YnRuOmVkaXQifSx7ImF1dGhvcml0eSI6InByb3RlY3Rpb246ZGV0YWlsIn0seyJhdXRob3JpdHkiOiJtZXNzYWdlOmJ0bjplZGl0In0seyJhdXRob3JpdHkiOiJiYW5uZXI6YnRuOmVkaXQifSx7ImF1dGhvcml0eSI6ImJhbm5lcjpidG46ZGVsZXRlIn0seyJhdXRob3JpdHkiOiJ2ZXJzaW9uOmJ0bjpkZWxldGUifSx7ImF1dGhvcml0eSI6Im1lc3NhZ2U6YnRuOmRlbGV0ZSJ9LHsiYXV0aG9yaXR5IjoiYXJ0aWNsZS1jYXRlZ29yeTpidG46ZWRpdCJ9LHsiYXV0aG9yaXR5IjoiYXJ0aWNsZTpidG46ZGVsZXRlIn0seyJhdXRob3JpdHkiOiJzZXR0aW5nOmJ0bjpwYXNzd29yZCJ9LHsiYXV0aG9yaXR5IjoibG9nOmJ0bjpjbGVhciJ9LHsiYXV0aG9yaXR5IjoiYmFubmVyLXBvc2l0aW9uOmJ0bjpkZWxldGUifSx7ImF1dGhvcml0eSI6ImZlZWRiYWNrOmJ0bjpkZWxldGUifSx7ImF1dGhvcml0eSI6InVzZXI6YnRuOmRlbGV0ZSJ9LHsiYXV0aG9yaXR5IjoiZGVwdDpidG46YWRkIn0seyJhdXRob3JpdHkiOiJyb2xlOmJ0bjphZGQifSx7ImF1dGhvcml0eSI6InN5c3RlbTpyb2xlIn0seyJhdXRob3JpdHkiOiJhcnRpY2xlLWNhdGVnb3J5OmJ0bjpkZWxldGUifSx7ImF1dGhvcml0eSI6InJvbGU6YnRuOmVkaXQifSx7ImF1dGhvcml0eSI6Im1lc3NhZ2U6bGlzdCJ9LHsiYXV0aG9yaXR5IjoiYWRtaW46YnRuOmVkaXQifSx7ImF1dGhvcml0eSI6Im1lbnU6YnRuOmFkZCJ9LHsiYXV0aG9yaXR5Ijoic3lzdGVtOmRlcHQifSx7ImF1dGhvcml0eSI6ImRlcHQ6YnRuOmVkaXQifSx7ImF1dGhvcml0eSI6InN5c3RlbTptZW51In0seyJhdXRob3JpdHkiOiJhZG1pbjpidG46YWRkIn0seyJhdXRob3JpdHkiOiJtZW51OmJ0bjplZGl0In0seyJhdXRob3JpdHkiOiJhZG1pbjpidG46ZGVsZXRlIn0seyJhdXRob3JpdHkiOiJkZXB0OmJ0bjpkZWxldGUifSx7ImF1dGhvcml0eSI6ImZlZWRiYWNrOmxpc3QifSx7ImF1dGhvcml0eSI6Im1lbnU6YnRuOmRlbGV0ZSJ9LHsiYXV0aG9yaXR5Ijoicm9sZTpidG46ZGVsZXRlIn0seyJhdXRob3JpdHkiOiJ2ZXJzaW9uOmxpc3QifV0sImV4cCI6MTczMzI4ODIyOH0.Ok75LmydeXFqg0sJfPjbp47AEuvGrPYooM-c9rCLyw4',
            'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
            'Content-Type': 'application/json'
        }

        response = requests.request("POST", url, headers=headers, data=payload,timeout=30,verify=False)

        result = response.json()
        if result.get('code')==0:
            self.token = result.get('data').get('token',{}).replace("Bearer ","")
            print('cache token 60*60*24')
            self.cache.set(self.cacheKey,self.token,ex=60*60*24)
            self.headers = {
                'token': f'{self.token}',
                'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
                'Content-Type': 'application/json',
                'Authorization': f'Bearer {self.token}'
                }
            print('login success')
            print(self.token)
        else:
            print('login failed')
            raise Exception(response.text)

    def genUrl(self, path):
        return self.url+path

    def execute_api(self,table_name,action,data_json:str,test=False):
        
        api_info = self.api_dict[(table_name,action)]
        
        if test:
            data_json = json.dumps(api_info['submit']) 

        if api_info['method'] == 'get':
            self.execute_get_api(api_info,data_json)
        elif api_info['method'] == 'post':
            self.execute_post_api(api_info,data_json)
            
        return self.results
    
    def execute_get_api(self,api_info,data_json):
        print(f"execute get api:{api_info['path']},data:{data_json}")
        url = self.genUrl(api_info['path'])
        if data_json:
            params = json.loads(data_json)
            response = requests.get(url, headers=self.headers, params=params)
        else:
            response = requests.get(url, headers=self.headers)
        results = response.json()
        if results.get('code')==0:
            self.results = json.dumps(results.get('data'))
        else:
            raise Exception(f'call {url} error: {response.text}')
    
    def execute_post_api(self,api_info,data_json):
        print(f"execute get api:{api_info['path']},data:{data_json}")
        url = self.genUrl(api_info['path'])
        response = requests.request("POST", url, headers=self.headers, data=data_json,verify=False)
        self.results = response.text
    @checkResponseJson
    def save_overall_market_trend(self,data):
        '''大盘指数历史行情'''

        url =self.genUrl('/overall_market_trend/batch_add')
        payload = json.dumps(data)

        response = requests.request("POST", url, headers=self.headers, data=payload,verify=False)

        return response
    @checkResponseJson
    def get(self,url_path):
        url = self.genUrl(url_path)
        payload = json.dumps({})
        response = requests.request("GET", url, headers=self.headers, data=payload,verify=False)
        return response
    
    @checkResponseJson
    def post(self,url_path,data):
        url = self.genUrl(url_path)
        payload = json.dumps(data)
        response = requests.request("POST", url, headers=self.headers, data=payload,verify=False)
        return response
    
    def overall_market_trend_Lastest_Record(self):
        url = "/overall_market_trend/getLatestRecord"
        return self.get(url)

    @checkResponseJson
    def save_shenwan_history(self,data):
        '''申万行业分类成分股变动历史'''
        url =self.genUrl('/shenwan_history/batch_add')

        payload = json.dumps(data)
        
        response = requests.request("POST", url, headers=self.headers, data=payload,verify=False)
        print(response.text)
        return response
    @checkResponseJson
    def save_shenwan_index_history(self,data):
        '''申万行业指数历史行情'''

        url =self.genUrl('/shenwan_index_history/batch_add')

        payload = json.dumps(data)

        response = requests.request("POST", url, headers=self.headers, data=payload,verify=False)
        return response
    @checkResponseJson
    def save_shenwan_industry(self,data):
        '''申万行业分类
        '''
        url =self.genUrl('/shenwan_industry/batch_add')

        payload = json.dumps(data)

        response = requests.request("POST", url, headers=self.headers, data=payload,verify=False)

        return response
    @checkResponseJson
    def save_stocks_custom_history(self,data):
        '''个股历史行情'''
        url =self.genUrl('/stocks_custom_history/batch_add')

        payload = json.dumps(data)

        response = requests.request("POST", url, headers=self.headers, data=payload,verify=False)
        print(response.text)
        return response
    @checkResponseJson
    def stocks_custom_history_factor(self,data):
        '''个股历史复权因子'''
        url =self.genUrl('/stocks_custom_history_factor/batch_add')
        payload = json.dumps(data)
        response = requests.request("POST", url, headers=self.headers, data=payload,verify=False)
        print(response.text)
        return response
    
    @checkResponseJson
    def CallBackCaulculateResult(self,data):
        '''测算结果回写
        {
            "caculateId": 871575821960089600,
            "ammount": 100000.15,
            "measureType": "虚假信息",
            "measureSubtype": "虚假公示",
            "beginDate": 19700416,
            "endDate": 19840219
        }
        '''
        url =self.genUrl("/stock_loss_caculation/caculate_callback")

        payload = json.dumps(data)

        response = requests.request("POST", url, headers=self.headers, data=payload,verify=False)

        return response
    @checkResponseJson
    def save_measure_history(self,data):
        url =self.genUrl('/measure_history/batch_add')

        payload = json.dumps(data)

        response = requests.request("POST", url, headers=self.headers, data=payload,verify=False)
        
        return response
    @checkResponseJson
    def get_latest_measure(self,measure_entity):

        url = self.genUrl(f"/measure_history/get-latest?measure_entity={measure_entity}")
        payload={}
        response = requests.request("GET", url, headers=self.headers, data=payload,verify=False)
        return response

    @checkResponseJson
    def save_stocks(self,data):

        url = self.genUrl("/stocks/batch_add")

        payload = json.dumps(data)

        response = requests.request("POST", url, headers=self.headers, data=payload,verify=False)

        return response
    @checkResponseJson
    def getStockLastData(self,stock):
        url = self.genUrl(f"/stocks_custom_history/getStockLastDate?stockId={stock}")
        payload={}

        response = requests.request("GET", url, headers=self.headers, data=payload,verify=False)
        print(response.text)
        return response
    
    @checkResponseJson
    def getSocktLastFetchDate(self,stock):
        url =self.genUrl(f"/stocks/getStockLastFetchDate?stockId={stock}")
        payload={}
        response = requests.request("GET", url, headers=self.headers, data=payload,verify=False)
        print(response.text)
        return response
    @checkResponseJson
    def updateSocktLastFetchDate(self,stock,date):
        url = self.genUrl(f"/stocks/updatFetchDate?stockId={stock}&fetchDate={date}")

        payload={}
        response = requests.request("GET", url, headers=self.headers, data=payload,verify=False)
        return response
    @checkResponseJson
    def batch_add_regional(self,datas):
        url = self.genUrl("/regional_info/batch_add")
        payload = json.dumps(datas)
        response = requests.request("POST", url, headers=self.headers, data=payload,verify=False)
        print(response.text)
        return response
    
    @checkResponseJson
    def get_task(self,local_ip,task_id=""):
        url = self.genUrl(f"/stock_loss_caculation/get-task?ip={local_ip}&calculateId={task_id}")
        response = requests.request("GET", url, headers=self.headers, data={},verify=False)
        # print(response.text)
        return response
    
    def import_real_measure(self,datas):
        '''导入真实监管数据'''
        return self.post("/measure_action_real/batch_add",datas)
    @checkResponseJson
    def uploadFile(self,file:BufferedReader,folder='guan_articl'):
        url = self.genUrl(f"/file/upload")
        payload={'folder':folder}
        files={'file':file}
        headers =copy.deepcopy(self.headers)
        headers.pop('Content-Type')
        response = requests.request("POST", url, headers=headers, data=payload, files=files,verify=False)
        # {  response example:
        #     "message": "Success",
        #     "code": 0,
        #     "data": {
        #         "url": "https://guan-1251451406.cos.ap-guangzhou.myqcloud.com/guan_articl/d51b8fb635dbf5cbf081d811bda82198.xlsx",
        #         "path": "guan_articl/d51b8fb635dbf5cbf081d811bda82198.xlsx"
        #     }
        # }
        return response
    @checkResponseJson
    def addMeasureHistorySingle(self,data):
        url = self.genUrl("/measure_history/add_update")
        payload = json.dumps(data,ensure_ascii=False)
        response = requests.request("POST", url, headers=self.headers, data=payload,verify=False)
        return response
    
    @checkResponseJson
    def addCaculateProcess(self,data):
        '''添加计算过程数据'''
        url = self.genUrl("/stock_loss_caculation_process/add_update")
        payload = json.dumps(data,ensure_ascii=False)
        # payload = json.dumps({
        #     "lossId": "1",
        #     "investInitDate": 1,
        #     "initStockQuant": 1,
        #     "violationId": 1,
        #     "qinquanLevel": 1,
        #     "commitDate": 1,
        #     "revealDate": 1,
        #     "benchMarkDate": 1,
        #     "benchMarkPrice": 1,
        #     "nominalLoss": 1,
        #     "sysLossRatio": 1,
        #     "nonSysLossRatio": 1,
        #     "realLoss": 1,
        #     "otherLoss": 1,
        #     "totalLoss": 1
        #     })
        
        response = requests.request("POST", url, headers=self.headers, data=payload)
        return response


if __name__ == "__main__":
    new_api = MxtfApi()
    # new_api_submit = {
    #     "stock_id":"000001",
    #     "start_date":"2024-01-01 00:00:00",
    #     "end_date":"2024-12-31 23:59:59"
    #     }
    # new_api_data_json = json.dumps(new_api_submit)
    # new_api.execute_api("stock_hist","select",new_api_data_json,False)

    # new_api_submit = {
    #     "symbol":"测试数据",
    #     "start_date":"2024-01-01 00:00:00",
    #     "end_date":"2024-12-31 23:59:59"
    #     }
    # new_api_data_json = json.dumps(new_api_submit)
    # new_api.execute_api("stock_hist","insert",new_api_data_json,True)
    # results = json.loads(new_api.results)
    with open('test.py','r') as f:
        new_api.uploadFile()
    